package com.jincheng.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Jane
 * @date 2024-11-18 10:59
 */

public class MybatisUtil {
    private static SqlSessionFactory factory;
    static {
        try {
            //声明配置文件名称
            String resorce = "mybatis-config.xml";
            //获取文件流
            InputStream is = Resources.getResourceAsStream(resorce);

            //工厂  设计模式 简单工厂设计模式
//            factory = new SqlSessionFactoryBuilder().build(is,"yjh");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            throw new RuntimeException("数据源获取失败",e);
        }
    }

    public static SqlSession createSqlSession(boolean flag){
        return factory.openSession(flag); //关闭事务
    }

    public static void closeSqlSession(SqlSession session){
        if (null !=session){
            session.close();
        }
    }
}
